package com.dhp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.InternalJSONUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dhp.bkapiclientsdk.BKapiClent;
import com.dhp.common.BaseResponse;
import com.dhp.common.ErrorCode;
import com.dhp.constant.CommonConstant;
import com.dhp.exception.BusinessException;
import com.dhp.exception.ThrowUtils;
import com.dhp.model.dto.interfaceInfo.InterfaceInfoQueryRequest;
import com.dhp.model.dto.interfaceInfo.InvokeRequest;
import com.dhp.model.dto.interfaceInfo.PublishInterfaceRequest;
import com.dhp.model.entity.*;
import com.dhp.model.enums.InterfaceStatusEnum;
import com.dhp.model.vo.InterfaceInfoVO;
import com.dhp.model.vo.PostVO;
import com.dhp.model.vo.UserVO;
import com.dhp.service.InterfaceInfoService;
import com.dhp.mapper.InterfaceInfoMapper;
import com.dhp.service.UserInterfaceInfoService;
import com.dhp.service.UserService;
import com.dhp.utils.SqlUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.parsson.JsonUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author Dhp
* @description 针对表【interface_info(接口信息)】的数据库操作Service实现
* @createDate 2024-07-26 16:28:17
*/
@Service
public class InterfaceInfoServiceImpl extends ServiceImpl<InterfaceInfoMapper, InterfaceInfo>
    implements InterfaceInfoService{

    @Autowired
    private UserService userService;

    @Autowired
    private BKapiClent bKapiClent;

    @Autowired
    private UserInterfaceInfoService userInterfaceInfoService;
    /**
     * 校验请求参数
     * @param interfaceInfo
     * @param add
     */
    @Override
    public void validInterfaceInfo(InterfaceInfo interfaceInfo, boolean add) {
        if (interfaceInfo == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String name = interfaceInfo.getName();
        String url = interfaceInfo.getUrl();
        String method = interfaceInfo.getMethod();

        // 创建时，参数不能为空
        if (add) {
            ThrowUtils.throwIf(StringUtils.isAnyBlank(name , url , method), ErrorCode.PARAMS_ERROR);
        }
        // 有参数则校验
        if (StringUtils.isNotBlank(name) && name.length() > 30) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "名称过长");
        }
        //todo 根据正则表达式判断url是否符合规范
    }

    @Override
    public QueryWrapper<InterfaceInfo> getQueryWrapper(InterfaceInfoQueryRequest interfaceInfoQueryRequest) {
        QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper<>();
        if (interfaceInfoQueryRequest == null) {
            return queryWrapper;
        }
        Long id = interfaceInfoQueryRequest.getId();
        String name = interfaceInfoQueryRequest.getName();
        String description = interfaceInfoQueryRequest.getDescription();
        String url = interfaceInfoQueryRequest.getUrl();
        Integer status = interfaceInfoQueryRequest.getStatus();
        Long userId = interfaceInfoQueryRequest.getUserId();
        String method = interfaceInfoQueryRequest.getMethod();
        String sortField = interfaceInfoQueryRequest.getSortField();
        String sortOrder = interfaceInfoQueryRequest.getSortOrder();
        
        // 拼接查询条件
        queryWrapper.like(StringUtils.isNotBlank(name), "name", name);
        queryWrapper.like(StringUtils.isNotBlank(description), "description", description);
        queryWrapper.like(StringUtils.isNotBlank(url), "url", url);
        queryWrapper.eq(ObjectUtils.isNotEmpty(status) , "status" , status);
        queryWrapper.like(StringUtils.isNotBlank(method), "method", method);
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    @Override
    public InterfaceInfoVO getInterfaceInfoVO(InterfaceInfo interfaceInfo, HttpServletRequest request) {
        InterfaceInfoVO interfaceInfoVO = InterfaceInfoVO.objToVo(interfaceInfo);
        return interfaceInfoVO;
    }

    @Override
    public Page<InterfaceInfoVO> getInterfaceInfoVOPage(Page<InterfaceInfo> interfaceInfoPage, HttpServletRequest request) {
        List<InterfaceInfo> interfaceInfoList = interfaceInfoPage.getRecords();
        Page<InterfaceInfoVO> interfaceInfoVOPage = new Page<>(interfaceInfoPage.getCurrent(), interfaceInfoPage.getSize(), interfaceInfoPage.getTotal());
        if (CollUtil.isEmpty(interfaceInfoList)) {
            return interfaceInfoVOPage;
        }
        // 1. 关联查询用户信息
        Set<Long> userIdSet = interfaceInfoList.stream().map(InterfaceInfo::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 填充信息
        List<InterfaceInfoVO> interfaceInfoVOList = interfaceInfoList.stream().map(interfaceInfo -> {
            InterfaceInfoVO interfaceInfoVO = InterfaceInfoVO.objToVo(interfaceInfo);
            Long userId = interfaceInfo.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                UserVO userVO = new UserVO();
                user = userIdUserListMap.get(userId).get(0);
                BeanUtils.copyProperties(user , userVO);
                interfaceInfoVO.setUser(userVO);
            }
            return interfaceInfoVO;
        }).collect(Collectors.toList());

        interfaceInfoVOPage.setRecords(interfaceInfoVOList);
        return interfaceInfoVOPage;
    }

    /**
     * 上线接口
     * @param publishInterfaceRequest
     * @return
     */
    @Override
    public Boolean publishInterface(PublishInterfaceRequest publishInterfaceRequest , HttpServletRequest request) {
        long id = publishInterfaceRequest.getId();
        if (id <= 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR , "接口id不符合规范");
        }

        //查询接口是否存在
        InterfaceInfo interfaceInfo = getById(id);
        if (null == interfaceInfo){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR , "接口不存在");
        }

        InvokeRequest invokeRequest = new InvokeRequest();
        BeanUtil.copyProperties(publishInterfaceRequest , invokeRequest);
        invokeRequest.setFromPublish(true);
        Object response = invokeInterface(invokeRequest, request);
        BaseResponse baseResponse = JSONUtil.toBean((String) response, BaseResponse.class);
        if (0 != baseResponse.getCode()){
            throw new BusinessException(ErrorCode.OPERATION_ERROR , "接口异常");
        }

        //更新接口状态
        interfaceInfo.setStatus(InterfaceStatusEnum.OPEN.getValue());
        return updateById(interfaceInfo);
    }

    @Override
    public Boolean offLineInterface(Long id) {
        if (id <= 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR , "接口id不符合规范");
        }

        //查询接口是否存在
        InterfaceInfo interfaceInfo = getById(id);
        if (null == interfaceInfo){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR , "接口不存在");
        }

        //更新接口状态
        interfaceInfo.setStatus(InterfaceStatusEnum.CLOSED.getValue());
        return updateById(interfaceInfo);

    }

    /**
     * 根据id获取接口信息
     * @param id
     * @return
     */
    @Override
    public InterfaceInfoVO getInterfaceById(Long id) {
        //判断接口是否存在
        InterfaceInfo interfaceInfo = getById(id);
        if (null == interfaceInfo){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR , "接口不存在");
        }
        InterfaceInfoVO interfaceInfoVO = InterfaceInfoVO.objToVo(interfaceInfo);
        return interfaceInfoVO;
    }

    /**
     * 在线调用接口
     * @param invokeRequest
     * @param request
     * @return
     */
    @Override
    public Object invokeInterface(InvokeRequest invokeRequest, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        BKapiClent userInvokeClient = new BKapiClent(loginUser.getAccessKey() , loginUser.getSecretKey());
        //接口是否存在
        InterfaceInfo interfaceInfo = getById(invokeRequest.getId());
        if (null == interfaceInfo){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR , "接口不存在");
        }
        if (Boolean.FALSE.equals(invokeRequest.getFromPublish()) && InterfaceStatusEnum.CLOSED.getValue().equals(interfaceInfo.getStatus())){
            throw new BusinessException(ErrorCode.OPERATION_ERROR , "该接口已关闭");
        }

        //校验用户是否仍有调用次数
        LambdaQueryWrapper<UserInterfaceInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInterfaceInfo::getInterfaceinfoId , invokeRequest.getId());
        queryWrapper.eq(UserInterfaceInfo::getUserid , loginUser.getId());
        UserInterfaceInfo userInterfaceInfo = userInterfaceInfoService.getOne(queryWrapper);
        if (null == userInterfaceInfo){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR , "您无权调用该接口");
        }else{
            int leftCount = userInterfaceInfo.getLeftNum();
            if (leftCount < 1){
                throw new BusinessException(ErrorCode.OPERATION_ERROR , "您的次数已用尽");
            }
        }

        //获取参数
        int startIndex = interfaceInfo.getUrl().indexOf("api");
        String originUrl = interfaceInfo.getUrl();
        String path = interfaceInfo.getUrl().substring(startIndex);
        String method = interfaceInfo.getMethod();
        String queryString = invokeRequest.getUserRequestParams();

        if(HttpMethod.GET.name().equals(method)){
            if (!StringUtils.isEmpty(queryString)){
                //构建参数
                Map<String , Object> parameterMap = new HashMap<>();
                String[] split = queryString.split("&");
                for (String s : split) {
                    String[] param = s.split("=");
                    if (param.length < 2){
                        throw new BusinessException(ErrorCode.PARAMS_ERROR);
                    }
                    parameterMap.put(param[0] , param[1]);
                }
                return userInvokeClient.doGetRequest(originUrl ,path , parameterMap);
            }
            return userInvokeClient.doGetRequest(originUrl , path , new HashMap<>());
        }else{
            if (!StringUtils.isEmpty(queryString)){
                return userInvokeClient.doPostRequest(originUrl , path , null , queryString);
            }
            return userInvokeClient.doPostRequest(originUrl , path , null , null);
        }
    }
}




